﻿using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using VM.CameraConfigs;
using VM.Common.Enums;
using VM.Common.EventMgrLib;
using VM.Common.Extension;
using VM.Common.Helper;
using VM.Core;
using VM.Dialogs.Views;
using VM.Events;
using VM.Models;

namespace VM.CameraSet
{
    [JsonObject(MemberSerialization.OptOut)]
    public class CameraSetViewModel : NotifyPropertyBase
    {
        #region Singleton

        private static readonly CameraSetViewModel _instance = new CameraSetViewModel();

        private CameraSetViewModel()
        {

        }

        [Newtonsoft.Json.JsonIgnore]
        public static CameraSetViewModel Ins => _instance;

        #endregion

        #region 属性

        //[Newtonsoft.Json.JsonIgnore]
        //public VMDisplayControl _mWindowH;
        //[Newtonsoft.Json.JsonIgnore]
        //public VMDisplayControl mWindowH
        //{
        //    get
        //    {
        //        if (_mWindowH == null)
        //        {
        //            _mWindowH = new VMDisplayControl();
        //        }
        //        return _mWindowH;
        //    }
        //}

        [Newtonsoft.Json.JsonIgnore]
        private int _SelectedIndex;
        [Newtonsoft.Json.JsonIgnore]
        public int SelectedIndex
        {
            get { return _SelectedIndex; }
            set { _SelectedIndex = value; RaisePropertyChanged(); }
        }

        [Newtonsoft.Json.JsonIgnore]
        public DispatcherTimer Timer_ContinuousAcq;

        /// <summary>相机列表</summary>
        [Newtonsoft.Json.JsonIgnore]
        public ObservableCollection<CameraBase> CameraModels { get; set; } = new ObservableCollection<CameraBase>();

        /// <summary>
        /// 相机插件字典
        /// </summary>
        public static Dictionary<string, PluginsInfo> PluginDic_Camera = InitializeCameraPlugins();

        /// <summary>
        /// 初始化相机插件字典
        /// </summary>
        /// <returns>初始化后的相机插件字典</returns>
        private static Dictionary<string, PluginsInfo> InitializeCameraPlugins()
        {
            var plugins = new Dictionary<string, PluginsInfo>();

            // 添加海康相机
            var hikVisionInfo = new PluginsInfo
            {
                ModuleName = "海康相机",
                Category = "相机",
                ModuleType = typeof(CameraHikVision),
            };

            plugins.Add(hikVisionInfo.ModuleName, hikVisionInfo);

            // 如果有其他相机，可以继续添加...
            // var otherCameraInfo = new PluginsInfo { ... };
            // plugins.Add(otherCameraInfo.ModuleName, otherCameraInfo);

            return plugins;
        }

        #endregion
        #region 数据接口
        [Newtonsoft.Json.JsonIgnore]
        private CameraBase _SelectedCameraModel;
        [Newtonsoft.Json.JsonIgnore]
        public CameraBase SelectedCameraModel
        {
            get { return _SelectedCameraModel; }
            set { Set(ref _SelectedCameraModel, value); }
        }

        /// <summary>
        /// 相机列表
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        private List<CameraInfoModel> _CameraNos = new List<CameraInfoModel>();
        [Newtonsoft.Json.JsonIgnore]
        public List<CameraInfoModel> CameraNos
        {
            get { return _CameraNos; }
            set { Set(ref _CameraNos, value); }
        }

        /// <summary>
        /// 选择相机
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        private CameraInfoModel _SelectedCameraNo = new CameraInfoModel();
        [Newtonsoft.Json.JsonIgnore]
        public CameraInfoModel SelectedCameraNo
        {
            get { return _SelectedCameraNo; }
            set { Set(ref _SelectedCameraNo, value); }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CameraInfoModel _CameraNo = new CameraInfoModel();
        [Newtonsoft.Json.JsonIgnore]
        public CameraInfoModel CameraNo
        {
            get { return _CameraNo; }
            set { _CameraNo = value; }
        }

        /// <summary>
        /// 检测相机类型
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        private List<string> _CameraTypes = new List<string>() { "海康相机" };
        [Newtonsoft.Json.JsonIgnore]
        public List<string> CameraTypes
        {
            get { return _CameraTypes; }
            set { _CameraTypes = value; }
        }

        /// <summary>
        /// 选择相机类型
        /// </summary>
        private CameraBase _cameraModule;
        [Newtonsoft.Json.JsonIgnore]
        private string _SelectedCameraType;
        [Newtonsoft.Json.JsonIgnore]
        public string SelectedCameraType
        {
            get { return _SelectedCameraType; }
            set
            {
                Set(ref _SelectedCameraType, value);
                if (_cameraModule == null || _cameraModule.GetType() != PluginDic_Camera[value].ModuleType)
                {
                    PluginsInfo pluginsInfo = PluginDic_Camera[value]; // 获取对应的插件信息
                    _cameraModule = (CameraBase)Activator.CreateInstance(pluginsInfo.ModuleType); // 实例化模块
                }
                CameraNos = _cameraModule.SearchCameras();
                SelectedCameraNo = CameraNos.FirstOrDefault();
            }
        }

        private string _buttonContent = "连续采集";
        public string ButtonContent
        {
            get => _buttonContent;
            set => Set(ref _buttonContent, value);
        }

        #endregion
        #region 指令
        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _DataOperateCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase DataOperateCommand
        {
            get
            {
                if (_DataOperateCommand == null)
                {
                    _DataOperateCommand = new CommandBase((obj) =>
                    {
                        switch (obj)
                        {
                            case "Search":
                                try
                                {
                                    Search(SelectedCameraType);
                                }
                                catch (Exception ex)
                                {

                                }
                                break;
                            case "Add":
                                try
                                {
                                    if (CameraSetView.Ins.cmbCameraNo.SelectedIndex == -1) return;
                                    int index = CameraModels.FindIndex(c => c.SerialNo == CameraSetView.Ins.cmbCameraNo.SelectedValue.ToString());
                                    if (index >= 0)
                                    {
                                        MessageView.Ins.MessageBoxShow("该设备已经添加列表!");
                                        return;
                                    }
                                    //根据选中的插件 new一个 模块
                                    PluginsInfo m_PluginsInfo = PluginDic_Camera[CameraTypes[CameraSetView.Ins.cmbCameraType.SelectedIndex]];
                                    CameraBase module = (CameraBase)Activator.CreateInstance(m_PluginsInfo.ModuleType);

                                    //确定新模块的不重名名称
                                    if (CameraModels != null)
                                    {
                                        if (CameraModels.Count > 0)
                                        {
                                            List<string> nameList = CameraModels.Select(c => c.CameraNo).ToList();
                                            while (true)
                                            {
                                                if (!nameList.Contains("Dev" + CameraBase.LastNo))
                                                {
                                                    break;//没有重名就跳出循环
                                                }
                                                CameraBase.LastNo++;
                                            }
                                        }
                                        else
                                        {
                                            CameraBase.LastNo++;
                                        }
                                    }
                                    module.CameraNo = "Dev" + CameraBase.LastNo;
                                    var cameraInfo = CameraSetView.Ins.cmbCameraNo.SelectedItem as CameraInfoModel;
                                    if (cameraInfo != null)
                                    {
                                        module.SerialNo = cameraInfo.SerialNO;
                                        module.CameraType = m_PluginsInfo.ModuleName;
                                        module.Remarks = $"{m_PluginsInfo.ModuleName}_{module.SerialNo}";
                                        module.ExtInfo = cameraInfo.ExtInfo;
                                        module.GetParams();
                                        CameraModels.Add(module);
                                        EventMgr.Ins.GetEvent<AddCameraEvent>().Publish(new AddCameraEventParamModel() { Camera = module, OperateType = eOperateType.Add });
                                    }
                                }
                                catch (Exception ex)
                                {

                                }
                                break;
                            case "Delete":
                                if (SelectedCameraModel == null) return;
                                ButtonContent = "连续采集";
                                SelectedCameraModel.DisConnectDev();
                                CameraModels.Remove(SelectedCameraModel);
                                break;
                            case "Modify":
                                IpConfigView.Ins.ShowDialog();
                                break;
                            default:
                                break;
                        }
                        SelectedIndex = CameraModels.Count - 1;
                        EventMgr.Ins.GetEvent<HardwareChangedEvent>().Publish();
                    });
                }
                return _DataOperateCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _ButtonOperateCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase ButtonOperateCommand
        {
            get
            {
                if (_ButtonOperateCommand == null)
                {
                    _ButtonOperateCommand = new CommandBase((obj) =>
                    {
                        switch (obj)
                        {
                            case "Connect":
                                if (SelectedCameraModel == null) return;
                                SelectedCameraModel.ConnectDev();
                                break;
                            case "Disconnect":
                                if (SelectedCameraModel == null) return;
                                SelectedCameraModel.DisConnectDev();
                                ButtonContent = "连续采集";
                                break;
                            case "SingleAcq":
                                ButtonContent = "连续采集";
                                if (SelectedCameraModel == null || !SelectedCameraModel.Connected) return;
                                SelectedCameraModel.EventWait.Reset();
                                SelectedCameraModel.CaptureSingleImage();
                                SelectedCameraModel.EventWait.WaitOne();

                                break;
                            case "ContinuousAcq":
                                if (SelectedCameraModel == null) return;
                                if (ButtonContent == "连续采集")
                                {
                                    ButtonContent = "停止采集";
                                    SelectedCameraModel.CaptureContinualImage(true);
                                    return;
                                }
                                else
                                {
                                    ButtonContent = "连续采集";
                                    SelectedCameraModel.CaptureContinualImage(false);
                                    return;
                                }
                            default:
                                break;
                        }
                    });
                }
                return _ButtonOperateCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _ActivatedCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase ActivatedCommand
        {
            get
            {
                if (_ActivatedCommand == null)
                {
                    _ActivatedCommand = new CommandBase((obj) =>
                    {
                        if (CameraSetView.Ins.IsClosed)
                        {
                            CameraSetView.Ins.IsClosed = false;
                        }

                    });
                }
                return _ActivatedCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _ConfirmCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase ConfirmCommand
        {
            get
            {
                if (_ConfirmCommand == null)
                {
                    _ConfirmCommand = new CommandBase((obj) =>
                    {
                        CameraSetView.Ins.Close();
                    });
                }
                return _ConfirmCommand;
            }
        }

        #endregion
        #region 方法

        public List<string> Search(string CameraType)
        {
            List<string> CameraNames = new List<string>();
            //if (CameraType != null && PluginService.PluginDic_Camera.ContainsKey(CameraType)) // 检查字典中是否包含指定的键
            //{
            //    SelectedCameraType = CameraType;
            //    if (_cameraModule == null || _cameraModule.GetType() != PluginService.PluginDic_Camera[CameraType].ModuleType)
            //    {
            //        PluginsInfo pluginsInfo = PluginService.PluginDic_Camera[CameraType]; // 获取对应的插件信息
            //        _cameraModule = (CameraBase)Activator.CreateInstance(pluginsInfo.ModuleType); // 实例化模块
            //    }
            //    CameraNos = _cameraModule.SearchCameras();
            //    SelectedCameraNo = CameraNos.FirstOrDefault();
            //    foreach (var item in CameraNos)
            //    {
            //        CameraNames.Add(item.SerialNO);
            //    }
            //}
            //else
            //{
            //    MessageView.Ins.MessageBoxShow($"不存在该相机类型: '{CameraType}' 。", eMsgType.Error);

            //}
            return CameraNames;
        }

        #endregion

    }
}
